package com.sdweizan.sdk.bytedance.config.impl;

import com.sdweizan.sdk.bytedance.bean.oauth2.BdAccessTokenResponse;
import com.sdweizan.sdk.bytedance.config.BdConfigStorage;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BdDefaultConfigStorageImpl implements BdConfigStorage, Serializable {
  private static final long serialVersionUID = 6487171407727416042L;

  @Getter @Setter protected volatile String appId; // 小程序appid
  @Getter @Setter protected volatile String secret; // 小程序密钥
  @Getter @Setter protected volatile String token; // Token(令牌)
  @Getter @Setter protected volatile String platformPublicKey; //平台公钥
  @Getter @Setter protected volatile String appPrivateKey; //应用私钥

  @Getter @Setter protected volatile String aesKey; //
  @Getter @Setter protected volatile String salt; // 支付系统秘钥

  @Getter protected volatile String accessToken;
  @Getter protected volatile String openAccessToken;
  @Getter protected volatile long expiresTime;
  @Getter protected volatile long openExpiresTime;
  @Getter protected volatile boolean autoRefreshToken = true;

  @Getter protected volatile int retrySleepMillis = 1000;
  @Getter protected volatile int maxRetryTimes = 5;

  @Getter protected volatile Lock accessTokenLock = new ReentrantLock();
  @Getter protected volatile Lock openAccessTokenLock = new ReentrantLock();

  @Override
  public boolean isAccessTokenExpired() {
    return System.currentTimeMillis() > expiresTime;
  }

  @Override
  public void expireAccessToken() {
    expiresTime = 0;
  }

  @Override
  public void updateAccessToken(BdAccessTokenResponse accessToken) {
    updateAccessToken(accessToken.getData().getAccessToken(), accessToken.getData().getExpiresIn());
  }

  @Override
  public void updateAccessToken(String accessToken, int expiresInSeconds) {
    this.accessToken = accessToken;
    expiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L;
  }

  @Override
  public boolean isOpenAccessTokenExpired() {
    return System.currentTimeMillis() > openExpiresTime;
  }

  @Override
  public void expireOpenAccessToken() {
    openExpiresTime = 0;
  }

  @Override
  public void updateOpenAccessToken(BdAccessTokenResponse openAccessToken) {
    updateOpenAccessToken(
        openAccessToken.getData().getAccessToken(), openAccessToken.getData().getExpiresIn());
  }

  @Override
  public void updateOpenAccessToken(String openAccessToken, int expiresInSeconds) {
    this.openAccessToken = openAccessToken;
    openExpiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L;
  }
}
